package itemlog

import (
	"sort"
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/dao/itemlogdao"
	"xr-game-server/entity"
	"xr-game-server/gameevent"
	"xr-game-server/module/protocol"
)

func itemChange(param any) {
	if param == nil {
		return
	}
	itemChangeData := param.(*gameevent.ItemChangeData)
	if itemChangeData == nil {
		return
	}
	itemLogs := itemlogdao.GetItemLog(itemChangeData.RoleId, Max)
	currentSize := len(itemLogs)
	//无法新加的数值
	tempModels := make([]*protocol.ItemModel, common.Zero)
	//先添加
	for _, item := range itemChangeData.Items {
		if currentSize >= Max {
			tempModels = append(tempModels, item)
			continue
		}
		//新加
		itemLog := entity.NewItemLog()
		itemLog.SetRoleId(itemChangeData.RoleId)
		itemLog.SetCurrent(item.Current)
		itemLog.SetVal(item.Val)
		itemLog.SetItemId(item.Id)
		itemLog.SetFail(item.Fail)
		itemLog.SetOld(item.Old)
		itemLog.SetTypeId(item.TypeId)
		if item.Source != nil {
			itemLog.SetSourceId(item.Source.Id)
		}
		itemlogdao.AddItemLog(itemLog, Max)
		currentSize++
	}
	cacheData := itemlogdao.GetItemLog(itemChangeData.RoleId, Max)
	currentSize = len(cacheData)
	currentSize--
	//开始处理无法添加的数值
	for _, item := range tempModels {
		if currentSize < common.Zero {
			break
		}
		now := time.Now()
		cacheData[currentSize].SetVal(item.Val)
		cacheData[currentSize].SetUpdatedAt(now)
		cacheData[currentSize].SetTypeId(item.TypeId)
		cacheData[currentSize].SetCreatedAt(now)
		cacheData[currentSize].SetItemId(item.Id)
		if item.Source != nil {
			cacheData[currentSize].SetSourceId(item.Source.Id)
		}
		cacheData[currentSize].SetOld(item.Old)
		cacheData[currentSize].SetCurrent(item.Current)
		cacheData[currentSize].SetFail(item.Fail)
		currentSize--
	}
	sort.Sort(ByUpdatedAt(itemLogs))
}
